<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="阶段名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入阶段名称"
          clearable
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="阶段描述" prop="courseDesc">
        <el-input
          v-model="queryParams.courseDesc"
          placeholder="请输入课程阶段描述"
          clearable
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="指导老师" prop="courseTutor">
        <el-input
          v-model="queryParams.courseTutor"
          placeholder="请输入指导老师姓名"
          clearable
          @keyup.enter="handleQuery"
          style="width: 120px"
        />
      </el-form-item>
      <el-form-item label="所属方向" prop="directionId">
        <el-select
          v-model="queryParams.directionId"
          placeholder="请选择所属方向"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="item in directionOptions"
            :key="item.id || item.directionId"
            :label="item.directionName"
            :value="item.id || item.directionId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          style="width: 120px"
        >
          <el-option label="未开课" value="0" />
          <el-option label="已开课" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:course:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:course:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:course:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:course:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="阶段ID" align="center" prop="courseId" width="70" />
      <el-table-column label="阶段名称" align="center" prop="courseName" width="130" />
      <el-table-column label="课程描述" align="center" prop="courseDesc" />
      <el-table-column label="指导老师" align="center" prop="courseTutor" width="120" />
      <el-table-column label="所属方向" align="center" width="120">
        <template #default="scope">
          {{ getDirectionName(scope.row.directionId) }}
        </template>
      </el-table-column>
      <el-table-column label="课程状态" align="center" prop="status" width="120">
        <template #default="scope">
          <span :class="scope.row.status === '0' ? 'status-not-start' : 'status-running'">
            {{ scope.row.status === '0' ? '未开课' : '已开课' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:course:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:course:remove']">删除</el-button>
          <el-button
             link
            type="success"
            icon="Operation"
            @click="handleStageClick(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="courseRef" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="阶段名称" prop="courseName"> 
          <el-input v-model="form.courseName" placeholder="请输入阶段名称" />
        </el-form-item>
        <el-form-item label="课程阶段描述" prop="courseDesc">
          <el-input v-model="form.courseDesc" placeholder="请输入课程阶段描述" />
        </el-form-item>
        <el-form-item label="指导老师姓名" prop="courseTutor">
          <el-input v-model="form.courseTutor" placeholder="请输入课程指导老师姓名" />
        </el-form-item>
        <el-form-item label="指导老师工号" prop="courseTutorId">
          <el-input v-model="form.courseTutorId" placeholder="请输入课程指导老师工号" />
        </el-form-item>
        <el-form-item label="课程图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action=""
            :auto-upload="false"
            :on-change="handleImageChange"
            :show-file-list="false"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="所属方向" prop="directionId">
          <el-select v-model="form.directionId" placeholder="请选择所属方向" style="width: 100%">
            <el-option
              v-for="item in directionOptions"
              :key="item.id || item.directionId"
              :label="item.directionName"
              :value="item.id || item.directionId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择课程状态" style="width: 100%">
            <el-option label="未开课" value="0" />
            <el-option label="已开课" value="1" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Course">
import { listCourse, getCourse, delCourse, addCourse, updateCourse } from "@/api/coursemanagement/course";
import { listDirection, getDirection } from "@/api/directionmanagement/direction";
import { useRouter } from "vue-router";
import { uploadImageFile } from "@/api/tool/oss";
import { Plus } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const router = useRouter();

const courseList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    courseName: null,
    courseDesc: null,
    courseTutorId: null,
    courseTutor: null,
    directionId: null,
    status: null,
  },
  rules: {
  },
  imageFile: null,
});

const { queryParams, form, rules } = toRefs(data);

// 方向选项列表
const directionOptions = ref([]);

// 方向名称缓存
const directionNames = ref({});

// 获取方向名称
function getDirectionName(directionId) {
  if (!directionId) return '';
  if (directionNames.value[directionId]) {
    return directionNames.value[directionId];
  }
  
  // 首先尝试从已加载的方向列表中获取
  const direction = directionOptions.value.find(item => item.directionId === directionId || item.id === directionId);
  if (direction) {
    directionNames.value[directionId] = direction.directionName;
    return direction.directionName;
  }
  
  // 如果列表中没有，再通过API获取
  getDirection(directionId).then(response => {
    const name = response.data?.directionName || response.data?.direction_name || directionId;
    directionNames.value[directionId] = name;
    // 强制更新视图
    courseList.value = [...courseList.value];
  });
  return '加载中...';
}

/** 查询方向列表 */
function getDirectionList() {
  listDirection({ pageNum: 1, pageSize: 100 }).then(response => {
    directionOptions.value = response.rows;
  });
}

// 预加载方向名称
const preloadDirectionNames = async () => {
  try {
    // 获取所有不重复的方向ID
    const uniqueDirectionIds = [...new Set(courseList.value.map(item => item.directionId).filter(id => id))];
    
    // 批量获取方向名称
    const promises = uniqueDirectionIds.map(directionId => {
      if (!directionNames.value[directionId]) {
        return getDirectionName(directionId);
      }
    }).filter(Boolean); // 过滤掉undefined
    
    // 等待所有请求完成
    await Promise.all(promises);
  } catch (error) {
    console.error('预加载方向名称失败:', error);
  }
}

/** 查询课程列表 */
function getList() {
  loading.value = true;
  listCourse(queryParams.value).then(response => {
    courseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    
    // 预加载方向名称
    preloadDirectionNames();
  }).catch(error => {
    console.error('获取课程列表失败:', error);
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    courseId: null,
    courseName: null,
    courseDesc: null,
    courseTutorId: null,
    courseTutor: null,
    directionId: null,
    status: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    image: null
  };
  data.imageFile = null;
  proxy.resetForm("courseRef");
}

// 处理图片上传
function handleImageChange(file) {
  data.imageFile = file.raw;
  // 创建临时URL用于预览
  form.value.image = URL.createObjectURL(file.raw);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.courseId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加课程";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _courseId = row.courseId || ids.value
  getCourse(_courseId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改课程";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["courseRef"].validate(valid => {
    if (valid) {
      proxy.$modal.loading("正在提交中...");
      // 如果有图片文件，先上传图片
      if (data.imageFile) {
        uploadImageFile(data.imageFile).then(response => {
          // 图片上传成功后，将图片URL添加到表单数据中
          form.value.image = response.msg;
          submitCourseData();
        }).catch(error => {
          proxy.$modal.closeLoading();
          proxy.$modal.msgError("图片上传失败");
        });
      } else {
        // 没有图片直接提交课程数据
        submitCourseData();
      }
    }
  });
}

/** 提交课程数据 */
function submitCourseData() {
  if (form.value.courseId != null) {
    updateCourse(form.value).then(response => {
      proxy.$modal.closeLoading();
      proxy.$modal.msgSuccess("修改成功");
      open.value = false;
      getList();
    }).catch(() => { proxy.$modal.closeLoading(); });
  } else {
    addCourse(form.value).then(response => {
      proxy.$modal.closeLoading();
      proxy.$modal.msgSuccess("新增成功");
      open.value = false;
      getList();
    }).catch(() => { proxy.$modal.closeLoading(); });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _courseIds = row.courseId || ids.value;
  proxy.$modal.confirm('是否确认删除课程ID为"' + _courseIds + '"的数据项？').then(function() {
    return delCourse(_courseIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/course/export', {
    ...queryParams.value
  }, `course_${new Date().getTime()}.xlsx`)
}

/** 项目名称点击事件 */
function handleStageClick(row) {
  // 跳转到课程详情页面，传递课程ID和名称作为参数
  router.push({
    path: "/coursemanagement/coursedetail",
    query: { id: row.courseId, courseName: row.courseName },
  });
}


// 在页面加载时获取方向列表
getDirectionList();
getList();
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
